package com.own.business.pay.core.util;

import com.alibaba.fastjson2.JSON;
import com.own.business.pay.common.exception.PayException;
import com.own.business.pay.core.aop.AopPayService;
import com.own.business.pay.core.base.BasePayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UnitePayRegisterUtil
 *
 * @author chenxueli
 * @date 2023-08-23 14:24:41
 */
@Slf4j
@Component
public class UnitePayRegisterUtil {

    private final Map<String, BasePayService> PAY_SERVICE_MAP = new HashMap<>();

    @Resource
    private List<BasePayService> payServiceList;

    @PostConstruct
    private void init() {
        for (var service : payServiceList) {
            var aop = service.getClass().getAnnotation(AopPayService.class);
            if (aop == null) {
                break;
            }
            PAY_SERVICE_MAP.put(aop.value().getType(), service);
        }
        log.info("成功加载支付方式【{}】", JSON.toJSONString(PAY_SERVICE_MAP.keySet()));
    }

    /**
     * 获取支付服务
     *
     * @param method 支付方式
     * @return 支付服务
     */
    public BasePayService getPayService(String method) {
        if (PAY_SERVICE_MAP.containsKey(method)) {
            return PAY_SERVICE_MAP.get(method);
        }
        throw new PayException("支付方式【{}】不存在");
    }

}
